﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Net;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace AzureDriveExplorer
{
    public partial class Account : Form
    {
        private bool newLine = false;
        Log log = new Log();
        Constant constant = new Constant();
        //Azure
        private static GetListVHD.AzureDriveExplorerServiceSoapClient list = new GetListVHD.AzureDriveExplorerServiceSoapClient();

        int numLanguage = 0;

        public Account(int NumLanguage)
        {
            numLanguage = NumLanguage;
            InitializeComponent();
            language();



            //enabled object
            txtUpload.Enabled = false;
            butSelectFile.Enabled = false;
            butDeleteStorage.Enabled = false;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            if (!File.Exists(Constant.FileConfig))
            {
                File.Create(Constant.FileConfig);
            }
            else
            {
                try
                {
                    // Create an instance of StreamReader to read from a file.
                    // The using statement also closes the StreamReader.
                    using (StreamReader sr = new StreamReader(Constant.FileConfig))
                    {
                        String line;
                        // Read and display lines from the file until the end of 
                        // the file is reached.
                        while ((line = sr.ReadLine()) != null)
                        {
                            listBox1.Items.Add(line);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Let the user know what went wrong.
                    MessageBox.Show(constant.idioma(numLanguage, 1), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //log.Logs("Error", ex.Message);
                }
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool error = false;


            txtAccountName.Text = txtAccountName.Text.Replace(" ", "");
            txtAccountkey.Text = txtAccountkey.Text.Replace(" ", "");
            txtContainerName.Text = txtContainerName.Text.Replace(" ", "");
            txtvhdName.Text = txtvhdName.Text.Replace(" ", "");

            if (txtAccountName.Text.Equals("") || txtAccountkey.Text.Equals("") || txtContainerName.Text.Equals("") || txtvhdName.Text.Equals(""))
            {
                MessageBox.Show(constant.idioma(numLanguage, 144), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var editLine = txtAccountName.Text + " " + txtAccountkey.Text + " " + txtContainerName.Text + " " + txtvhdName.Text;

            if (newLine)
                listBox1.Items.Add(editLine);
            else
            {
                if (listBox1.SelectedIndex > -1)
                    listBox1.Items[listBox1.SelectedIndex] = editLine;
                else
                    listBox1.Items.Add(editLine);
            }

            if (checkBox1.Checked && !txtUpload.Text.Equals(""))
            { error = Uploader(); }

            newLine = false;
            if (!error)
                textboxClear();

            writeFile();
        }

        protected bool Uploader()
        {
            bool error = false;
            try
            {
                this.Enabled = false;
                // Use the storage emulator.

                CloudStorageAccount account = null;

                account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + txtAccountName.Text + ";AccountKey=" + txtAccountkey.Text);

                // Create the Blob service client.
                CloudBlobClient client = account.CreateCloudBlobClient();

                // Create the container for the drive if it does not already exist.
                CloudBlobContainer container = new CloudBlobContainer(txtContainerName.Text, client);
                container.CreateIfNotExist();

                //container.Uri
                string blobUri = "http://" + container.Uri.Host + "/" + txtContainerName.Text + "/" + txtvhdName.Text;

                // check args
                if (txtUpload.Text.Equals("") || container.Uri.Equals("") || txtvhdName.Text.Equals(""))
                {
                    MessageBox.Show(constant.idioma(numLanguage, 138), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;
                }

                using (FileStream file = File.OpenRead(txtUpload.Text))
                {
                    int pageSize = 1024 * 1024;
                    int numPages = (int)(file.Length / pageSize);
                    long blobSize = (file.Length / 512) * 512; // page size needs to be multiple of 512
                    if ((file.Length % 512) > 0)
                    {
                        // adjust to the next 512 bytes boundary
                        blobSize += 512;
                        //Output("Warning : file size adjusted to {0} (512 boundary)", blobSize);
                    }
                    //Trace("File size : {0:0,0}", file.Length);
                    //Trace("Page size : {0:0,0}", pageSize);
                    //Trace("Pages     : {0}", numPages);
                    //Trace("Remainder : {0:0,0}", blobSize - pageSize * numPages);
                    //Trace("");

                    //Trace("Create blob : {0}", blobUri);
                    CloudBlobClient blobStorage = account.CreateCloudBlobClient();
                    CloudPageBlob blob = blobStorage.GetPageBlobReference(blobUri);

                    blob.Properties.ContentType = "binary/octet-stream";
                    blob.Create(blobSize);

                    byte[] page = new byte[pageSize];
                    using (MemoryStream stmPage = new MemoryStream(page))
                    {
                        // process all pages until last
                        for (int i = 0; i < numPages; i++)
                        {
                            // status update
                            labInfo.Text = ("Uploading - " + (i + 1) + " / " + numPages.ToString());

                            // write page to storage
                            file.Read(page, 0, pageSize);
                            stmPage.Seek(0, SeekOrigin.Begin);
                            blob.WritePages(stmPage, i * pageSize);
                        }

                        // process last page
                        if (blobSize > numPages * pageSize)
                        {
                            int remain = (int)(blobSize - (numPages * pageSize));
                            page = new byte[remain];    // allocate a clean buffer, padding with zero
                            //Trace("Last page : {0:0,0}", remain);
                            //Trace("Padding   : {0:0,0}", file.Length % 512);

                            using (MemoryStream stmLast = new MemoryStream(page))
                            {
                                // write page to storage
                                file.Read(page, 0, remain);
                                stmLast.Seek(0, SeekOrigin.Begin);
                                blob.WritePages(stmLast, numPages * pageSize);
                            }
                        }
                    }

                    // status update
                    MessageBox.Show(constant.idioma(numLanguage, 139), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(constant.idioma(numLanguage, 131) + ex, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                error = true;
            }
            finally
            {
                this.Enabled = true;
            }

            return error;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            newLine = true;
            listBox1.ClearSelected();
            txtAccountName.Text = labAccountName.Text;
            txtAccountkey.Text = labAccountKey.Text;
            txtContainerName.Text = labContainerName.Text;
            txtvhdName.Text = labvhdName.Text;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (listBox1.SelectedIndex == -1)
                return;

            string Config = listBox1.Items[listBox1.SelectedIndex].ToString();

            string[] vecConfig = Config.Split(' ');
            for (int i = 0; i < vecConfig.Length; i++)
                switch (i)
                {
                    case 0: txtAccountName.Text = vecConfig[i]; break;
                    case 1: txtAccountkey.Text = vecConfig[i]; break;
                    case 2: txtContainerName.Text = vecConfig[i]; break;
                    case 3: txtvhdName.Text = vecConfig[i]; break;


                }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            textboxClear();
        }

        protected void writeFile()
        {
            using (StreamWriter sw = new StreamWriter(Constant.FileConfig))
            {
                sw.Write("");
                for (int i = 0; i < listBox1.Items.Count; i++)
                    sw.WriteLine(listBox1.Items[i].ToString());

                sw.Close();

            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                if (DialogResult.No == MessageBox.Show(constant.idioma(numLanguage, 140), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                { return; }

                writeFile();
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                textboxClear();
            }
            else
            {
                MessageBox.Show(constant.idioma(numLanguage, 2), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void textboxClear()
        {
            txtAccountName.Text = "";
            txtAccountkey.Text = "";
            txtContainerName.Text = "";
            txtvhdName.Text = "";
            txtUpload.Text = "";
            checkBox1.Checked = false;
        }

        private void language()
        {

            this.Text = constant.idioma(numLanguage, 100);
            this.labAccountName.Text = constant.idioma(numLanguage, 101);
            this.labAccountKey.Text = constant.idioma(numLanguage, 102);
            this.labContainerName.Text = constant.idioma(numLanguage, 103);
            this.labvhdName.Text = constant.idioma(numLanguage, 104);

            this.butNewLine.Text = constant.idioma(numLanguage, 105);
            this.butsave.Text = constant.idioma(numLanguage, 106);
            this.butClear.Text = constant.idioma(numLanguage, 107);
            this.butDelete.Text = constant.idioma(numLanguage, 108);

            this.tabControl1.TabPages[0].Text = constant.idioma(numLanguage, 109);
            this.tabControl1.TabPages[1].Text = constant.idioma(numLanguage, 110);

            this.checkBox1.Text = constant.idioma(numLanguage, 111);
            this.butSelectFile.Text = constant.idioma(numLanguage, 112);

            this.butConnect.Text = constant.idioma(numLanguage, 113);
            this.butDeleteStorage.Text = constant.idioma(numLanguage, 108);

            this.labName.Text = constant.idioma(numLanguage, 101);
            this.labKey.Text = constant.idioma(numLanguage, 102);
            this.labStorage.Text = constant.idioma(numLanguage, 114);

            this.label1.Text = constant.idioma(numLanguage, 101);
            this.label2.Text = constant.idioma(numLanguage, 102);
            this.button1.Text = constant.idioma(numLanguage, 113);
            this.button3.Text = constant.idioma(numLanguage, 145);
            this.button2.Text = constant.idioma(numLanguage, 146);
            this.progressBar1.Visible = false;
        }

        private void butSelectFile_Click(object sender, EventArgs e)
        {


            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtUpload.Text = openFileDialog1.FileName;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                txtUpload.Enabled = true;
                butSelectFile.Enabled = true;
            }
            else
            {
                txtUpload.Enabled = false;
                butSelectFile.Enabled = false;
            }
        }

        private void butConect_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Equals("") || txtkey.Text.Equals(""))
            {
                MessageBox.Show(constant.idioma(numLanguage, 141), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            listFile.Items.Clear();

            // Use the storage emulator.
            CloudStorageAccount account = null;
            var filesList = new List<string>();

            //account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + txtAccountName.Text + ";AccountKey=" + txtAccountkey.Text);
            account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + txtName.Text + ";AccountKey=" + txtkey.Text);

            // Create the Blob service client.
            CloudBlobClient client = account.CreateCloudBlobClient();


            foreach (Microsoft.WindowsAzure.StorageClient.CloudBlobContainer str in client.ListContainers())
            {

                CloudBlobDirectory topLevelDirectory = client.GetBlobDirectoryReference(str.Uri.ToString());

                //CloudBlobDirectory subDirectory = topLevelDirectory.GetSubdirectory("/mydir1");

                IEnumerable<IListBlobItem> blobItems = topLevelDirectory.ListBlobs();
                foreach (IListBlobItem blobItem in blobItems)
                {
                    if (Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(".VHD") || Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(""))
                        listFile.Items.Add(blobItem.Uri.AbsolutePath.ToString());

                }
            }

            //only if list have information
            if (listFile.Items.Count > 0)
                butDeleteStorage.Enabled = true;
        }

        private void butDeleteStorage_Click(object sender, EventArgs e)
        {

            if (listFile.SelectedIndex == -1)
            {
                MessageBox.Show(constant.idioma(numLanguage, 142), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtName.Text.Equals("") || txtkey.Text.Equals(""))
            {
                MessageBox.Show(constant.idioma(numLanguage, 141), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (DialogResult.No == MessageBox.Show(constant.idioma(numLanguage, 143), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            { return; }

            string[] InfoVHD = listFile.SelectedItem.ToString().Split('/');

            string error = list.DeleteDriver(txtName.Text, txtkey.Text, InfoVHD[1], InfoVHD[2], Constant.key());

            if (error.Length > 0)
                MessageBox.Show(constant.idioma(numLanguage, 131) + error, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                butConect_Click(sender, e);
            }

            if (listFile.Items.Count == 0)
                butDeleteStorage.Enabled = false;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (textBox1.Text.Equals("") || textBox2.Text.Equals(""))
            {
                MessageBox.Show(constant.idioma(numLanguage, 141), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            listBox2.Items.Clear();

            // Use the storage emulator.
            CloudStorageAccount account = null;
            var filesList = new List<string>();

            //account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + txtAccountName.Text + ";AccountKey=" + txtAccountkey.Text);
            account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + textBox1.Text + ";AccountKey=" + textBox2.Text);

            // Create the Blob service client.
            CloudBlobClient client = account.CreateCloudBlobClient();


            foreach (Microsoft.WindowsAzure.StorageClient.CloudBlobContainer str in client.ListContainers())
            {

                CloudBlobDirectory topLevelDirectory = client.GetBlobDirectoryReference(str.Uri.ToString());

                //CloudBlobDirectory subDirectory = topLevelDirectory.GetSubdirectory("/mydir1");

                IEnumerable<IListBlobItem> blobItems = topLevelDirectory.ListBlobs();
                foreach (IListBlobItem blobItem in blobItems)
                {
                    if (Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(".VHD") || Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(""))
                        listBox2.Items.Add(blobItem.Uri.ToString());

                }
            }

            //only if list have information
            if (listBox2.Items.Count > 0)
                button2.Enabled = true;
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox3.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex > -1 && !textBox3.Text.Equals(""))
            {
                this.progressBar1.Visible = true;
                string[] name= listBox2.SelectedItem.ToString().Split('/');
                WebClient webClient = new WebClient();
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed1);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged1);
                webClient.DownloadFileAsync(new Uri(listBox2.SelectedItem.ToString()), textBox3.Text + "\\" + name[name.Length - 1]);

            }
        }

        private void ProgressChanged1(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label4.Text = progressBar1.Value.ToString() + "%";
            label4.Refresh();
        }

        private void Completed1(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show(constant.idioma(numLanguage, 125));
            this.progressBar1.Visible = false;
            label4.Text = "";
            
        }

    }
}
